import React, { useEffect, useMemo, useState } from 'react';
import styles from './TodoTable.module.less'; // 导入 Less 模块
import { RightOutlined } from '@ant-design/icons'; // 引入更多按钮的图标
import { ICompany, ITarget, IWorkTask } from '@/ts/core';
import orgCtrl from '@/ts/controller';
import { kernel } from '@/ts/base';
import { useHistory } from 'react-router-dom';
import { Modal } from 'antd';
import TaskContent from '@/executor/tools/task';
import { IWorkDarft } from '@/ts/core/work/draft';
import { IAssignTask } from '@/ts/core/work/assign';
import { IOrder } from '@/ts/core/mall/order/order';
import DraftWork from '@/executor/tools/task/start/draftWork';
import { AssignStatusType } from '@/ts/base/enum';
import AssignLayout from '@/components/DataPreview/assign/assignLayout';
import { EmptyAssign } from '@/components/DataPreview/assign';
import PreviewLayout from '@/components/DataPreview/layout';

interface TodoTableProps {
  target: ITarget;
}

interface IWorkList {
  id: string;
  type: string;
  title: string;
  unit: string;
  date: string;
}

const TYPE_MAPPING: Record<string, string> = {
  todo: '待办',
  order: '订单',
  task: '任务',
  draft: '草稿',
};

const TAB_TYPES = [
  { key: 'all', label: '全部' },
  { key: 'todo', label: '待办' },
  { key: 'order', label: '订单' },
  { key: 'task', label: '任务' },
  { key: 'draft', label: '草稿' },
];

const TodoTable: React.FC<TodoTableProps> = ({ target }) => {
  const [activeTab, setActiveTab] = useState('all');
  const [workList, setWorkList] = useState<IWorkList[]>([]);
  const [selectedItem, setSelectedItem] = useState<
    IWorkTask | IWorkDarft | IAssignTask | IOrder
  >();
  const [selectedItemType, setSelectedItemType] = useState<string>('');
  const [modalVisible, setModalVisible] = useState(false);
  const history = useHistory();
  // 根据activeTab筛选数据
  const filteredWorkList = useMemo(() => {
    if (activeTab === 'all') {
      return workList;
    }
    return workList.filter((item) => item.type === TYPE_MAPPING[activeTab]);
  }, [workList, activeTab]);
  useEffect(() => {
    const loadData = async () => {
      if (target.typeName == '单位') {
        const assignTask = await (target as ICompany).loadAssignTasks();
        const order = await (target as ICompany).loadAllOrder();
        const draft = await orgCtrl.work.loadDraft();
        const todos = await orgCtrl.work.loadTodos(false, target.id);
        let all = [];
        if (todos.length > 0) {
          for (const item of todos) {
            let title = item.name;
            let date = item.metadata.createTime;
            let result = await kernel.queryEntityById({ id: item.metadata.belongId });
            all.push({
              id: item.metadata.id,
              type: '待办',
              title: title,
              unit: result.data.name,
              date: date,
            });
          }
        }
        if (draft.length > 0) {
          for (const item of draft) {
            let result = await kernel.queryEntityById({ id: item.metadata.belongId });
            all.push({
              id: item.metadata.id,
              type: '草稿',
              title: item.name,
              unit: result.data.name,
              date: item.metadata.createTime,
            });
          }
        }
        if (assignTask.length > 0) {
          for (const item of assignTask) {
            let result = await kernel.queryEntityById({ id: item.metadata.belongId });
            all.push({
              id: item.metadata.id,
              type: '任务',
              title: item.name,
              unit: result.data.name,
              date: item.metadata.createTime,
            });
          }
        }
        if (order.length > 0) {
          for (const item of order) {
            let result = await kernel.queryEntityById({ id: item.metadata.belongId });
            all.push({
              id: item.metadata.id,
              type: '订单',
              title: item.name,
              unit: result.data.name,
              date: item.metadata.createTime,
            });
          }
        }
        setWorkList(
          all.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()),
        );
      }
    };
    loadData();
  }, [target]);
  // 处理行点击事件
  const handleRowClick = async (item: IWorkList) => {
    const worktask = await findWorkTask(item);
    setSelectedItem(worktask);
    setModalVisible(true);
  };

  // 关闭弹窗
  const handleCloseModal = () => {
    setModalVisible(false);
    setSelectedItem(undefined);
  };
  const findWorkTask = async (item: IWorkList) => {
    let worktask = undefined;
    if (item.type == '待办') {
      const todos = await orgCtrl.work.loadTodos();
      if (todos.length > 0) {
        worktask = todos.find((part) => part.id == item.id);
        setSelectedItemType('待办');
      }
    } else if (item.type == '草稿') {
      const draft = await orgCtrl.work.loadDraft();
      if (draft.length > 0) {
        worktask = draft.find((part) => part.id == item.id);
        setSelectedItemType('草稿');
      }
    } else if (item.type == '订单') {
      const order = await (target as ICompany).loadAllOrder();
      if (order.length > 0) {
        worktask = order.find((part) => part.id == item.id);
        setSelectedItemType('订单');
      }
    } else if (item.type == '任务') {
      const assignTask = await (target as ICompany).loadAssignTasks();
      if (assignTask.length > 0) {
        worktask = assignTask.find((part) => part.id == item.id);
        setSelectedItemType('任务');
      }
    }
    return worktask;
  };
  const renderEntityBody = (entity: any, children?: React.ReactNode) => {
    return <PreviewLayout entity={entity}>{children && children}</PreviewLayout>;
  };
  const renderModalContent = () => {
    if (!selectedItem) return null;

    switch (selectedItemType) {
      case '待办':
        return (
          <TaskContent current={selectedItem as IWorkTask} finished={handleCloseModal} />
        );
      case '草稿':
        return (
          <DraftWork current={selectedItem as IWorkDarft} finished={handleCloseModal} />
        );
      case '订单':
        // 目前不知道是哪个组件 暂时用TaskContent
        return (
          <TaskContent current={selectedItem as IWorkTask} finished={handleCloseModal} />
        );
      case '任务':
        if ((selectedItem as IAssignTask).taskStatus == AssignStatusType.EMPTY) {
          return renderEntityBody(
            selectedItem as IAssignTask,
            <EmptyAssign assignTask={selectedItem as IAssignTask} />,
          );
        } else {
          return <AssignLayout current={selectedItem as IAssignTask} />;
        }
      default:
        return <div>未知类型的内容</div>;
    }
  };

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <h2 className={styles.title}>待办事项</h2>
        <div className={styles.tabContainer}>
          {TAB_TYPES.map((tab) => (
            <button
              key={tab.key}
              className={`${styles.tabButton} ${
                activeTab === tab.key ? styles.active : ''
              }`}
              onClick={() => setActiveTab(tab.key)}>
              {tab.label}
            </button>
          ))}
          <button
            className={styles.moreButton}
            onClick={() => {
              history.push('./work');
            }}>
            更多 <RightOutlined />
          </button>
        </div>
      </div>
      <div className={styles.tableContainer}>
        {filteredWorkList.length === 0 ? (
          <div className={styles.emptyState}>
            <img src="img/emptyData.png" alt="暂无数据" className={styles.emptyImage} />
          </div>
        ) : (
          <table className={styles.table}>
            <thead>
              <tr>
                <th className={styles.typeColumn}>类型</th>
                <th className={styles.titleColumn}>标题</th>
                <th className={styles.departmentColumn}>发起单位</th>
                <th className={styles.date}>日期</th>
              </tr>
            </thead>
            <tbody>
              {filteredWorkList.map((item) => (
                <tr
                  key={item.id}
                  onClick={async () => {
                    await handleRowClick(item);
                  }}
                  className={styles.clickableRow}>
                  <td className={styles.typeCell}>
                    {TAB_TYPES.find((t) => t.key === item.type.toLowerCase())?.label ||
                      item.type}
                  </td>
                  <td className={styles.titleCell}>
                    <span className={styles.textEllipsis} title={item.title}>
                      {item.title}
                    </span>
                  </td>
                  <td className={styles.departmentCell}>{item.unit}</td>
                  <td className={styles.dateCell}>
                    {new Date(item.date).toLocaleString()}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
      {modalVisible && (
        <Modal
          title="待办事项详情"
          visible={modalVisible}
          onCancel={handleCloseModal}
          footer={null}
          width={'100%'}
          destroyOnClose // 关闭时销毁子元素
          bodyStyle={{ height: '1000px' }}>
          {selectedItem && renderModalContent()}
        </Modal>
      )}
    </div>
  );
};

export default TodoTable;
